/**
 * <p>
 * 版权所有：中企动力
 * </p>
 * <p>
 * 未经本公司许可，不得以任何方式复制或使用本程序任何部分
 * </p>
 */
package com.ce.pms.common.service.impl;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ce.pms.common.annotation.NoDACL;
import com.ce.pms.common.dao.IDataRightDao;
import com.ce.pms.common.dao.ISecRightDao;
import com.ce.pms.common.dao.ISecUserDao;
import com.ce.pms.common.model.SecRight;
import com.ce.pms.common.model.SecRightBuilding;
import com.ce.pms.common.model.SecRightPrecinct;
import com.ce.pms.common.model.SecUser;
import com.ce.pms.common.model.SecUserRelationRight;
import com.ce.pms.common.model.SysInfo;
import com.ce.pms.common.service.IDataRightService;
import com.ce.pms.common.util.PmsUtilityComparator;
import com.ce.pms.common.vo.EmployeeRightVO;
import com.ce.pms.exception.DataAccessException;
import com.ce.pms.house.dao.IBuildingDao;
import com.ce.pms.house.dao.IPrecinctDao;
import com.ce.pms.house.model.BuildingDomain;
import com.ce.pms.house.service.IBuildingService;
import com.ce.pms.house.service.IManageAreaService;
import com.ce.pms.house.vo.BuildingVO;
import com.ce.pms.house.vo.CompanyVO;
import com.ce.pms.house.vo.ManageOrgVO;
import com.ce.pms.house.vo.PrecinctVO;
import com.ce.util.BlankUtil;
import com.sitechasia.webx.core.support.Page;

/**
 * 
 * @author <a href="mailto:i0o@live.cn">黄腾飞</a>
 * @Created 2008-10-20
 */

public class DataRightServiceImpl implements IDataRightService {
	private IManageAreaService	manageAreaService;

	private IBuildingService	buildingService;

	private IDataRightDao		dataRightDao;

	private ISecUserDao			secUserDao;

	private ISecRightDao		secRightDao;

	private IPrecinctDao		precinctDao;

	private IBuildingDao		buildingDao;

	/**
	 * @param manageAreaService the manageAreaService to set
	 */
	public void setManageAreaService(IManageAreaService manageAreaService) {
		this.manageAreaService = manageAreaService;
	}

	/**
	 * @param buildingService the buildingService to set
	 */
	public void setBuildingService(IBuildingService buildingService) {
		this.buildingService = buildingService;
	}

	/**
	 * @param dataRightDao the dataRightDao to set
	 */
	public void setDataRightDao(IDataRightDao dataRightDao) {
		this.dataRightDao = dataRightDao;
	}

	/**
	 * @param secUserDao the secUserDao to set
	 */
	public void setSecUserDao(ISecUserDao secUserDao) {
		this.secUserDao = secUserDao;
	}

	/**
	 * @param secRightDao the secRightDao to set
	 */
	public void setSecRightDao(ISecRightDao secRightDao) {
		this.secRightDao = secRightDao;
	}

	/**
	 * @param precinctDao the precinctDao to set
	 */
	public void setPrecinctDao(IPrecinctDao precinctDao) {
		this.precinctDao = precinctDao;
	}

	/**
	 * @param buildingDao the buildingDao to set
	 */
	public void setBuildingDao(IBuildingDao buildingDao) {
		this.buildingDao = buildingDao;
	}

	// 楼栋代码
	private final String	BUILDING_CODE	= "002";

	// 管理区代码
	private final String	PRECINCT_CODE	= "001";

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ce.pms.common.service.IDataRightService#getManageList()
	 */
	@NoDACL
	public Map<CompanyVO, Map<ManageOrgVO, Map<PrecinctVO, List<BuildingVO>>>> getManageTree() {
		// 收费管理区
		List<PrecinctVO> precinctList = manageAreaService
				.getAllChargePrecinct();

		// 管理处,物业公司只有一个
		Map<CompanyVO, List<ManageOrgVO>> manageOrgMapTmp = (Map<CompanyVO, List<ManageOrgVO>>) (manageAreaService
				.queryCompanyManageOrgTreeList().get(0));

		List<CompanyVO> companyList = manageAreaService.findAllCompany();

		Map<CompanyVO, Map<ManageOrgVO, Map<PrecinctVO, List<BuildingVO>>>> companyMap = new HashMap<CompanyVO, Map<ManageOrgVO, Map<PrecinctVO, List<BuildingVO>>>>();
		for (CompanyVO companyVO : companyList) {
			List<ManageOrgVO> manageOrgList = manageOrgMapTmp.get(companyVO);
			// 管理处
			Map<ManageOrgVO, Map<PrecinctVO, List<BuildingVO>>> manageOrgMap = new HashMap<ManageOrgVO, Map<PrecinctVO, List<BuildingVO>>>();
			for (ManageOrgVO manageOrg : manageOrgList) {
				// 管理区
				Map<PrecinctVO, List<BuildingVO>> precinctMap = new HashMap<PrecinctVO, List<BuildingVO>>();
				for (PrecinctVO precinctVO : precinctList) {
					if (precinctVO.getManageOrgId() == manageOrg.getKeyword()) {
						List<BuildingVO> buildingVoList = buildingService
								.queryBuildListByPrecinctId(precinctVO
										.getKeyword());
						// ((ArrayList<BuildingVO>)buildingVoList).

						Collections.sort(buildingVoList, PmsUtilityComparator
								.getComparator());

						precinctMap.put(precinctVO, buildingVoList);
					}
				}
				manageOrgMap.put(manageOrg, precinctMap);
			}
			companyMap.put(companyVO, manageOrgMap);
		}

		return companyMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ce.pms.common.service.IDataRightService#saveDataRight(java.lang.Long,
	 * java.lang.Long,
	 * com.ce.pms.common.service.IDataRightService.DataRightType,
	 * java.lang.Long[])
	 */
	public boolean saveDataRight(Long creator, Long userId,
			DataRightType dataRightType, Long[] ids) {
		return saveDataRight(creator, userId, dataRightType, ids, true);
	}

	public boolean changePrecDataRight(Long creator, Long[] ids) {
		return false;
	}

	/*
	 * 保存数据权限 (non-Javadoc)
	 * 
	 * @see
	 * com.ce.pms.common.service.IDataRightService#SaveDataRight(java.lang.Long,
	 * com.ce.pms.common.service.IDataRightService.DataRightType,
	 * java.lang.String[])
	 */
	private boolean saveDataRight(Long creator, Long userId,
			DataRightType dataRightType, Long[] ids, boolean isDel) {
		// 检查用户
		SecUser secUser = secUserDao.findById(userId);
		if (secUser == null) {
			throw new DataAccessException("No exists User!");
		} else {
			// 删除该用户原来的权限
			if (isDel) {
				secUserDao.deleteDataRightByUserId(userId);
			}
		}

		SysInfo sysInfo = new SysInfo(creator, new Date(System
				.currentTimeMillis()));

		String rightTypeCode = dataRightType.equals(DataRightType.PRECINCT) ? PRECINCT_CODE
				: BUILDING_CODE;

		if (!BlankUtil.isBlank(ids)) {
			for (Long id : ids) {

				switch (dataRightType) {
					case PRECINCT:
						SecRight secRightPrecinct = new SecRightPrecinct();
						((SecRightPrecinct) secRightPrecinct)
								.setPrecinct(precinctDao.findById(id));
						secRightPrecinct.setSysInfo(sysInfo);

						// 保存权限
						SecRight tmpPrecinct = secRightDao
								.saveObject(secRightPrecinct);

						SecUserRelationRight surrPrecinct = new SecUserRelationRight(
								secUser, tmpPrecinct, id, rightTypeCode);

						dataRightDao.saveObject(surrPrecinct);

						List<BuildingDomain> buildingList = buildingDao
								.getBuildingListByPrecinctId(id);

						Long[] buildingIds = new Long[buildingList.size()];
						for (int i = 0; i < buildingIds.length; i++) {
							buildingIds[i] = ((BuildingDomain) buildingList
									.get(i)).getKeyword();
						}
						//
						saveDataRight(creator, userId, DataRightType.BUILDING,
								buildingIds, false);
						break;
					case BUILDING:

						SecRight secRightBuilding = new SecRightBuilding();
						((SecRightBuilding) secRightBuilding)
								.setBuilding(buildingDao.findById(id));
						secRightBuilding.setSysInfo(sysInfo);

						// 保存权限
						SecRight tmpBuilding = secRightDao
								.saveObject(secRightBuilding);
						System.out.println(tmpBuilding.getRightId());
						SecUserRelationRight surrBuilding = new SecUserRelationRight(
								secUser, tmpBuilding, id, rightTypeCode);

						dataRightDao.saveObject(surrBuilding);
						break;
				}

			}
		}

		// 权限id

		// SecUserRelationRight surr = new SecUserRelationRight();
		// surr.setSecUser(secUser);
		// surr.setSecRight(secRight);
		// surr
		// .setTypeCode(dataRightType.equals(DataRightType.PRECINCT) ?
		// PRECINCT_CODE
		// : BUILDING_CODE);

		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ce.pms.common.service.IDataRightService#isBuilDing(java.lang.Long)
	 */
	public boolean isPrecinctRight(Long userId) {
		return (dataRightDao.getPrecinctRight(userId)).size() > 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ce.pms.common.service.IDataRightService#queryEmployeeDataRight(com
	 * .ce.pms.common.vo.EmployeeRightVO, java.lang.Integer, java.lang.Integer)
	 */
	public Page queryEmployeeDataRight(EmployeeRightVO employee,
			Integer pageNO, Integer pageSize) {
		Page page = secUserDao.getEmployeeList(
				employee.getUserCode() == null ? "" : employee.getUserCode(),
				employee.getEmployeeName() == null ? "" : employee
						.getEmployeeName(), pageNO, pageSize);

		List list = page.getResult();

		List result = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			result.add(resultToEmployeeRightVo(obj));
		}
		page.setResult(result);

		return page;
	}

	/**
	 * 
	 * @param obj
	 * 
	 * @return
	 * @author <a href="mailto:i0o@live.cn">黄腾飞</a>
	 * @created 2008-10-23
	 */
	private EmployeeRightVO resultToEmployeeRightVo(Object[] obj) {
		EmployeeRightVO empRightVo = new EmployeeRightVO();
		// USER_ID
		empRightVo.setDeptId(obj[1] == null ? null : ((BigInteger) obj[1])
				.longValue());
		empRightVo.setEmployeeName(obj[2] == null ? null : (String) obj[2]);
		empRightVo.setSex(obj[3] == null ? null : ((BigInteger) obj[3])
				.longValue());
		empRightVo.setIdTypeId(obj[4] == null ? null : ((BigInteger) obj[4])
				.longValue());
		empRightVo.setIdNo(obj[5] == null ? null : (String) obj[5]);
		empRightVo.setUserId(obj[6] == null ? null : ((BigInteger) obj[6])
				.longValue());
		empRightVo.setUserCode(obj[7] == null ? null : (String) obj[7]);
		empRightVo.setDeptName(obj[8] == null ? null : (String) obj[8]);
		empRightVo.setIdTypeDisplay(obj[9] == null ? null : (String) obj[9]);

		if (empRightVo.getSex() != null) {
			empRightVo
					.setSexDisplay(empRightVo.getSex() == Long.valueOf(1) ? "男"
							: "女");
		}

		return empRightVo;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ce.pms.common.service.IDataRightService#getUserDataRight(java.lang
	 * .Long)
	 */
	public Long[] getUserDataRight(Long userId) {
		if (hasUserDataRight(userId)) {
			if (isPrecinctRight(userId)) {
				return secRightDao.getPrecinctRight(userId);
			} else {
				return secRightDao.getBuildingRight(userId);
			}
		} else {
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ce.pms.common.service.IDataRightService#hasUserDataRight(java.lang
	 * .Long)
	 */
	public boolean hasUserDataRight(Long userId) {
		// TODO Auto-generated method stub
		return (dataRightDao.getUserDataRight(userId)).size() > 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ce.pms.common.service.IDataRightService#getDataRightByUserId(java
	 * .lang.Long, java.lang.Long)
	 */
	public boolean getDataRightByUserId(Long userId, Long hoursId) {
		List<?> list = dataRightDao.getDataRightByUserId(userId, hoursId);
		return list.size() > 0;
	}
}
